package com.gw.business.analysis.task;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.gw.business.analysis.model.UserTrackDataAverage;
import com.gw.business.analysis.service.UserTrackDataAverageService;
import com.gw.business.analysis.service.UserTrackDataStatisticsService;
import com.gw.business.common.util.DateUtil;
import com.gw.platform.logger.Log;

/**
 * user_track_data_average 表数据添加
 * 
 * 类功能： 求不同来源、媒介   每月（访问、模拟、真实、咨询、入金）平均值
 *
 * 实现基本逻辑：通过已算好的userTrackDataStatistics（每天各小时 访问、模拟、真实、咨询、入金的统计数） 数据，与每月总天数相除求得平均值
 *
 * <p>
 * 创建者:关博
 * </p>
 * <p>
 * 创建时间:2015-03-06
 * </p>
 * <p>
 * 修改者:
 * </p>
 * <p>
 * 修改时间:
 * </p>
 * <p>
 * 修改原因：
 * </p>
 * <p>
 * 审核者:
 * </p>
 * <p>
 * 审核时间:
 * </p>
 * <p>
 * 审核意见：
 * </p>
 *
 */

@Component
public class UserTrackDataAverageTask{
	@Resource
	public UserTrackDataAverageService userTrackDataAverageService;
	
	@Resource
	private UserTrackDataStatisticsService userTrackDataStatisticsService;
	
	//@Scheduled(cron = "0 40 18 * * ?")
	@Scheduled(cron = "0 10 0 1 * ?")
    public void InitDate(){
		Log.info(this.getClass(), "UserTrackDataAverageTask开始-->");
		
		long start = System.currentTimeMillis();
		 
		//后60分钟的数据进行统计   当前默认下一月数据读取
		Date  halfTime=DateUtil.addMonths(new Date(), -1);
		String year=DateUtil.getDateFormat(halfTime, "yyyy");
		String mouth=DateUtil.getDateFormat(halfTime, "MM");
		
	    Calendar rightNow = Calendar.getInstance();
	    rightNow.setTime(halfTime);
	    int maxDay=rightNow.getActualMaximum(Calendar.DAY_OF_MONTH);  //月天数
		
		//对求和后的数据 进行 对上个月的天数 求平均值 
		List<UserTrackDataAverage> new_list=userTrackDataStatisticsService.getMouthCountByctmcmdAndutmcsr(year,mouth);
		
		List<UserTrackDataAverage> old_list=userTrackDataAverageService.getSourceByDataTime(year,mouth);
		
		Map<String, UserTrackDataAverage> base_map=new HashMap<String, UserTrackDataAverage>();
		
		List<UserTrackDataAverage> update_items=new ArrayList<UserTrackDataAverage>();
		
		UserTrackDataAverage obj=null;
		//平均值计算，  保留两位小数
		for (UserTrackDataAverage base : new_list) {
			if(base==null)continue;
			Log.info(this.getClass(), base.getDataTime()+"---"+base.getUtmcmd()+"--"+base.getUtmcsr());
			
			obj=new UserTrackDataAverage();
			obj.setDataTime(base.getDataTime());
			obj.setUtmcmd(base.getUtmcmd());
			obj.setUtmcsr(base.getUtmcsr());
			obj.setAdvisoryCountAverage(scale(base.getAdvisoryCountAverage(),maxDay,"advisoryCountAverage"));
			obj.setDemoCountAverage(scale(base.getDemoCountAverage(),maxDay,"demoCountAverage"));
			obj.setDepositCountAverage(scale(base.getDepositCountAverage(), maxDay, "depositCountAverage"));
			obj.setRealCountAverage(scale(base.getRealCountAverage(),maxDay,"realCountAverage"));
			obj.setVisitCount(scale(base.getVisitCount(), maxDay, "visitCount"));
			
			String yymmdd=DateUtil.getDateDayFormat(obj.getDataTime());
			String key=yymmdd+""+obj.getUtmcmd()+""+obj.getUtmcsr();
			base_map.put(key, obj);
		}
		
		
		//前后数据对比以  key=yymmdd+""+obj.getUtmcmd()+""+obj.getUtmcsr() 对比判断
		//循环已算的旧数据。  区分出那些数据插入，更新
		for (UserTrackDataAverage old : old_list) {
			if(old==null)continue;
			String yymmdd=DateUtil.getDateDayFormat(old.getDataTime());
			String key=yymmdd+""+old.getUtmcmd()+""+old.getUtmcsr();
			
			UserTrackDataAverage newObj=base_map.get(key);
			if(newObj!=null){//要对比 是否值有变化，进行更新操作  那对应KEY的地方设置成NULL     map剩下的数据 都是插入
				UserTrackDataAverage updateObj=contrastObj(old,newObj);
				if(updateObj!=null){
					//插入到update表  这个key的value null
					update_items.add(updateObj);
					//base_map.put(key,null);
				}
				base_map.remove(key);
			}
		}
		
		//循环update list  和剩下的map obj
		for (UserTrackDataAverage userTrackDataAverage : update_items) {
			userTrackDataAverageService.update(userTrackDataAverage);
		}

		Iterator<String> it=base_map.keySet().iterator();
		while(it.hasNext()){
			String key=it.next();
			UserTrackDataAverage insetObj=base_map.get(key);
			if(insetObj!=null)
			userTrackDataAverageService.insert(insetObj);
		}
		
		Log.info(this.getClass(), "UserTrackDataAverageTask结束，执行时间(s)：-->" + (System.currentTimeMillis()-start)/1000);
	}
	
	/**
	 * 前后对象对比。
	 * 把有修改的值放入 old对象里面 返回其对象 保留id 做更新 old->o new->n
	 * @param o
	 * @param n
	 * @return
	 */
	private UserTrackDataAverage  contrastObj(UserTrackDataAverage o,UserTrackDataAverage n){
		Boolean update=false;
		
		if(o.getAdvisoryCountAverage()!=n.getAdvisoryCountAverage()){
			o.setAdvisoryCountAverage(n.getAdvisoryCountAverage());
			update=true;
		}
		
		if(o.getDemoCountAverage()!=n.getDemoCountAverage()){
			o.setDemoCountAverage(n.getDemoCountAverage());
			update=true;
		}
		
		if(o.getDepositCountAverage()!=n.getDepositCountAverage()){
			o.setDepositCountAverage(n.getDepositCountAverage());
			update=true;
		}
		
		if(o.getRealCountAverage()!=n.getRealCountAverage()){
			o.setRealCountAverage(n.getRealCountAverage());
			update=true;
		}
		
		if(o.getVisitCount()!=n.getVisitCount()){
			o.setVisitCount(n.getVisitCount());
			update=true;
		}
		
		if(update)
			return o ;
		else 
			return null;
	}
	
	/**
	 * 根据天数 求平均值
	 * @param s
	 * @param maxDay
	 * @param error
	 * @return
	 */
	private double scale(double s,int maxDay,String error){
		try{
			double average=s/maxDay;
			BigDecimal bd = new BigDecimal(average);  
		    return	bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		}catch (Exception e) {
			Log.info(this.getClass(), "userTrackDataAverageTask  count:"+s+"-"+error);
			return 0d;
		}
	}
}
